import {
	getToken,
	setToken,
	setUserInfo,
	getUserInfo
} from '@/common/js/auth.js'

import {
	getUser
} from '@/api/user.js'

const user = {
	namespaced: true,
	state: {
		token: '',
		userInfo: {}
	},
	getters: {
		userInfo(state) {
			if (!state.userInfo.userId) {
				return getUserInfo();
			} else {
				return state.userInfo;
			}
		},
		token(state) {
			if (!state.token) {
				return getToken();
			} else {
				return state.token;
			}
		}
	},
	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
			setToken(token)
		},
		SET_USER_INFO: (state, userInfo) => {
			state.userInfo = userInfo;
			setUserInfo(userInfo)
			console.log(userInfo);
		},
	},
	actions: {
		// 获取用户信息
		GetInfo({
			commit
		}) {
			return new Promise((resolve, reject) => {
				getUser().then(res => {
					const user = res.data.sysUser
					commit('SET_USER_INFO', user)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
	}
}

export default user
